import axios from "axios";

localStorage.setItem("token", 'e522f1c7af3f7ad1e840f6843bdb83f0');
let baseUrl = '/data';

const instance = axios.create({
    timeout: 20000,
    baseURL: baseUrl // 根据自己配置的反向代理去设置不同环境的baseUrl
});


instance.defaults.headers.post['Content-Type'] = 'application/json';


/** 添加请求拦截器 **/
instance.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['authorization'] = token //在请求头中加入token
    }
    config.headers['Content-Type'] = 'multipart/form-data';  // 转换请求格式
    return config
}, error => {
    return Promise.reject(error)
});


/** 添加响应拦截器  **/
instance.interceptors.response.use(response => {
    if (response.status === 200) {
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response.data.msg)
    }
}, error => {
    if (error.response) {
        if (error.response.status === 401) {
            this.props.history.push('/login');
        }
        return Promise.reject(error)
    } else {
        return Promise.reject('请求超时, 请刷新重试')
    }
});


export const get = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: 'get',
            url,
            params,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
};


export const post = (url, data, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: 'post',
            url,
            data,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}
